package com.shulidata.mock.controller.base;

import com.alibaba.fastjson.JSON;
import com.shulidata.mock.utils.GenericException;
import com.shulidata.mock.utils.Result;
import com.shulidata.mock.utils.Servlets;
import com.shulidata.mock.utils.SysCode;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.TypeMismatchException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 远程调用Controller基类，只要用户处理业务异常
 */
public class BaseRestController {

    private static final Logger logger = LogManager.getLogger(BaseRestController.class.getName());
    
    @ExceptionHandler
    public Object handlerException(HttpServletRequest request, Exception e) {

        logger.error("请求接口 ==> {}\n请求参数 ==> {}",
                request.getRequestURI(),
                JSON.toJSONString(Servlets.getRequestParams(request)),
                e);

        // 异常类型判断，返回不同的错误代码
        // 1.业务自定义的异常
        if (e instanceof GenericException) {
            return new Result(((GenericException) e).getCode(), e.getMessage());
        }
        // 2.Spring MVC 参数绑定失败异常
        else if (e instanceof BindException) {
            return new Result(SysCode.ERR_PARAM);
        }
        // 3.Spring MVC 参数不匹配异常
        else if (e instanceof TypeMismatchException) {
            return new Result(SysCode.ERR_PARAM, "参数不匹配");
        }
        else if (e instanceof MissingServletRequestParameterException) {
            return new Result(SysCode.ERR_PARAM, "参数不存在或类型错误");
        }
        // n.未知异常
        else {
            return new Result(SysCode.ERR_SERVER);
        }

    }


}
